<?php
namespace Admin\Model;
use Think\Model;

class AdminModel extends Model{

    CONST LOGIN_CHECK = 4; // 自动验证-登录

    // 自动验证
    protected $_validate = array(
        array('username', '6,20', '账号长度不符,请保持在6-20个字符之内',self::EXISTS_VALIDATE, 'length',self::MODEL_BOTH),
        array('username','','该账号已被使用',self::EXISTS_VALIDATE,'unique',self::MODEL_BOTH),
        array('password', '6,30', '密码长度不符,请保持在6-30个字符之内',self::EXISTS_VALIDATE,'length',self::MODEL_INSERT),
        array('password', '6,30', '密码长度不符,请保持在6-30个字符之内2',self::VALUE_VALIDATE,'length',self::MODEL_UPDATE),

        //通用
        array('realname','/^[\x{4e00}-\x{9fa5}]+$/u','请填写中文的姓名',self::EXISTS_VALIDATE,'regex',self::MODEL_BOTH),
        array('mobile','/^\d{11}$/','请正确填写手机号码',self::EXISTS_VALIDATE,'regex',self::MODEL_BOTH),
        array('email','email','请正确填写邮箱地址',self::EXISTS_VALIDATE,'regex',self::MODEL_BOTH),

        // 登录检测
        array('username','require','账号必须填写！',self::MUST_VALIDATE, 'regex',self::LOGIN_CHECK),
        array('username', '4,20', '账号长度不符,请保持在4-20个字符之内',self::MUST_VALIDATE, 'length',self::LOGIN_CHECK),
        array('password','require','密码必须填写！',self::MUST_VALIDATE, 'regex',self::LOGIN_CHECK),
        array('verify','require','验证码必须填写！',self::MUST_VALIDATE, 'regex',self::LOGIN_CHECK),
        array('verify', '4', '验证码长度不符！',self::MUST_VALIDATE,'length',self::LOGIN_CHECK),
        array('verify','checkCode','验证码错误！',self::MUST_VALIDATE, 'callback',self::LOGIN_CHECK),
    );

    // 自动完成
    protected $_auto = array (
        array('password','getPassword',self::MODEL_UPDATE,'callback'),
        array('password','getPassword',self::MODEL_INSERT,'callback'),
        array('encrypt','getEncrypt',self::MODEL_UPDATE,'callback'),
        array('encrypt','getEncrypt',self::MODEL_INSERT,'callback'),
    );


    // 检测验证码
    public function checkCode($code){
        $Verify = new \Think\Verify();
        if(!$Verify->check($code, 1)) return false;
        return true;
    }

    // 登录检测
    public function login($username,$password,$remember=0){
        $admin = $this->where(array('username'=>$username))->find();
        if(!$admin){
            $this->error = '账号不存在';
            return false;
        }

        if(!$admin['status']){
            $this->error='账号已被禁用';
            return false;
        };

        $pass = $this->getPassword($password,$admin['encrypt']);

        if($pass != $admin['password']){
            $this->error = '密码错误';
            return false;
        }

        // 添加认证
        $this->adminInfo($admin);

        // 记住登录
        if($remember) $this->adminToken('add',$admin);

        // 成功登录
        return $admin;
    }



    /**
     * 自动验证或对比密码
     * @param string $str 密码
     * @param string $encrypt 密码密匙
     * @return bool|string
     */
    public function getPassword($str='',$encrypt=''){
        if(empty($str)) return false;
        if(empty($encrypt)){
            $this->encrypt=$encrypt = \Org\Util\String::randString(6);
        }
        return md5(sha1($str) . $encrypt);
    }


    /**
     * 添加session认证
     * @param array $admin 用户登录的信息
     */
    public function adminInfo($admin=array()){
        $admin_info = array(
            'id'=>$admin['id'],
            'username'=>$admin['username'],
        );
        session('adminInfo',$admin_info);
    }


    /**
     * 添加cookie持久认证
     * @param string $type 类型,add/check
     * @param array  $admin 用户信息
     * @return bool
     */
    public function adminToken($type='check',$admin=array()){
        switch ($type) {
            case 'add':
                if(empty($admin)) return false;
                $token = array();
                $token['token_time'] = time() + 3600 * 24 * 7;
                $token['token'] = md5($admin['username'].$token['token_time']);
                if( $this->where("id={$admin['id']}")->save($token) ){
                    cookie('admin_token', $token['token'], 3600 * 24 * 7);
                }else{
                    return false;
                }
                break;
            case 'check':
                $token = cookie('admin_token');
                if(!$token){ return false; }
                // 强制清除无效/过期cookie持久认证
                $admin = $this->where("token='{$token}'")->find();
                if( !$admin || $admin['token_time'] < time() ){
                    cookie('admin_token',null);
                    return false;
                }

                // 重新添加session认证
                $this->adminInfo($admin);
                return $admin['id'];
                break;
        }
        return true;
    }

    // 获取加密
    public function getEncrypt(){
        if(empty($this->encrypt)) return false;
        return $this->encrypt;
    }
}